﻿/*
   Selecting the window to work on
   Created by Randall Maas, Wednesday October 14 2009
   Copyright (c) 2009, Randall Maas
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

   Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

   Neither the name of Blackwood Designs, LLC nor the names of its contributors
   may be used to endorse or promote products derived from this software without
   specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
   THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System . Collections . Generic;
using System . Diagnostics;
using System . Threading;
using System . Windows . Forms;

static partial class Program
{
   /// <summary>
   /// Helper delegate when searching for the right window
   /// </summary>
   /// <param name="I"></param>
   /// <returns>true if the window matches, false otherwise</returns>
   delegate bool M(IntPtr I);

   /// <summary>
   /// Creates a delegate that matches window title or process name
   /// </summary>
   static void FindWins()
   {
      Dictionary<IntPtr, WinMass> W1 = new Dictionary<IntPtr, WinMass>();
      if ((null == AppName || "" == AppName) && IntPtr . Zero == AppId)
        {
           Win32 . WinEnumerate(delegate(IntPtr Wnd)
            {
               if (Win32 . IsTool(Wnd) || ! Win32 . IsVisible(Wnd))
                 return true;
               RECT Rect;
               Win32 . GetWindowRect(Wnd, out Rect);
               if (Rect . Left < -10000 && Rect . Top < -10000)
                 return true;

               WinMass M;
               if (Ws . TryGetValue(Wnd, out M))
                 W1 [Wnd] = M;
                else
                 W1 [Wnd] = new WinMass(Wnd);
                return true;
            });
           Ws = W1;
           return;
        }

      // Match by window title or application name 
      // I heard once that upper case is a more stable matching case across locales
      // Maybe should use ToUpperInvariant?
      string N1 = AppName . ToUpper();
      M A1 = delegate(IntPtr Wnd)
        {
           if (Win32 . IsTool(Wnd) || ! Win32 . IsVisible(Wnd))
             return false;
           RECT Rect;
           Win32 . GetWindowRect(Wnd, out Rect);
           if (Rect . Left < -10000 && Rect . Top < -10000)
             return false;

           // First check to see if the title matches
           if (null != N1)
             {
                string S = Win32 . Title(Wnd);
                if (null != S && S . ToUpper() . Trim() == N1)
                  return true;
             }

           // Next check the window identifier
           if (IntPtr . Zero != AppId)
             {
                IntPtr Id = Win32 . WinId(Wnd);
                if (AppId == Id)
                  return true;
             }

           // Next, get the process for the window ...
           using (Process P = Win32 . Process(Wnd))
           {
              // Okay, check the name
              if (null != N1 && P . ProcessName . ToUpper() . Trim() == N1)
                return true;

              // And then check the id
              if (IntPtr . Zero != AppId && P . Id == (int) AppId)
                return true;
           }
           return false;
        };

      // Now perform the search
      Win32 . WinEnumerate(delegate(IntPtr H)
        {
           if (!A1(H))
             return true;

           WinMass M;
           if (Ws . TryGetValue(H, out M))
             W1 [H] = M;
            else
             W1 [H] = new WinMass(H);
           return true;
        });
      Ws = W1;
   }

}
